import { openDatabase } from '../db/init'
import { v4 as uuidv4 } from 'uuid'
import log from 'electron-log'

/**
 * 视频服务类
 */
export class VideoService {
  /**
   * 获取视频的所有标签
   * @param {string} videoPath 视频路径
   * @returns {Promise<Array>} 标签数组
   */
  static async getTags(videoPath) {
    const db = await openDatabase()
    const normalizedPath = videoPath.replace('safe-file://', '')
    
    const video = db.prepare(
      'SELECT id FROM videos WHERE path = ?'
    ).get(normalizedPath)
    
    if (!video) {
      log.warn('找不到视频记录:', normalizedPath)
      return []
    }

    return db.prepare(`
      SELECT 
        vts.id,
        vts.start_time,
        vts.end_time,
        vts.description,
        t.name,
        t.color
      FROM video_tag_segments vts
      JOIN tags t ON vts.tag_id = t.id
      WHERE vts.video_id = ?
      ORDER BY vts.start_time
    `).all(video.id)
  }

  /**
   * 创建或更新视频记录
   * @param {string} filePath 视频文件路径
   * @param {string} name 视频名称
   * @returns {Promise<Object>} 视频记录
   */
  static async createOrUpdateVideo(filePath, name) {
    const db = await openDatabase()
    let video = db.prepare('SELECT id FROM videos WHERE path = ?').get(filePath)
    
    if (!video) {
      const videoId = uuidv4()
      db.prepare(`
        INSERT INTO videos (id, path, name, last_accessed)
        VALUES (?, ?, ?, CURRENT_TIMESTAMP)
      `).run(videoId, filePath, name)
      video = { id: videoId }
    } else {
      db.prepare(`
        UPDATE videos 
        SET last_accessed = CURRENT_TIMESTAMP
        WHERE id = ?
      `).run(video.id)
    }
    
    return video
  }

  /**
   * 更新视频时长
   * @param {string} videoPath 视频路径
   * @param {number} duration 视频时长
   */
  static async updateDuration(videoPath, duration) {
    const db = await openDatabase()
    db.prepare(
      `UPDATE videos 
       SET duration = ?
       WHERE path = ?`
    ).run(duration, videoPath)
  }

  /**
   * 搜索标签
   * @param {string} query 搜索关键词
   * @returns {Promise<Array>} 搜索结果
   */
  static async searchTags(query) {
    const db = await openDatabase()
    
    if (!query) {
      return db.prepare(`
        SELECT 
          vts.id,
          vts.video_id,
          v.path as video_path,
          vts.start_time,
          vts.end_time,
          vts.description,
          t.name,
          t.color
        FROM video_tag_segments vts
        JOIN videos v ON vts.video_id = v.id
        JOIN tags t ON vts.tag_id = t.id
        ORDER BY v.path, vts.start_time
      `).all()
    }

    const searchTerms = query.split(' ').filter(term => term.trim())
    if (searchTerms.length === 0) return []

    const conditions = searchTerms.map(() => 't.name LIKE ?').join(' OR ')
    const params = searchTerms.map(term => `%${term}%`)

    return db.prepare(`
      SELECT DISTINCT
        vts.id,
        vts.video_id,
        v.path as video_path,
        vts.start_time,
        vts.end_time,
        vts.description,
        t.name,
        t.color
      FROM video_tag_segments vts
      JOIN videos v ON vts.video_id = v.id
      JOIN tags t ON vts.tag_id = t.id
      WHERE ${conditions}
      ORDER BY v.path, vts.start_time
    `).all(...params)
  }
} 